package stat

import (
	"log"
	"time"
)

type Counter struct {
	commitCh chan bool
	succeed  int
	failed   int
	total    int

	quit chan struct{}
}

//NewCounter provide a counter to record result
func NewCounter() *Counter {
	return &Counter{
		commitCh: make(chan bool, 100),
		quit:     make(chan struct{}),
	}
}

//Start open rountine to run
func (c *Counter) Start() {
	go c.loop()

}
func (c *Counter) Stop() {
}

//post result
func (c *Counter) PostCommitResult(flag bool) {
	select {
	case c.commitCh <- flag:
	case <-c.quit:
	}
}

func (c *Counter) loop() {
	statTimer := time.NewTicker(3 * time.Minute)
	for {
		select {
		//record status
		case result := <-c.commitCh:
			if result == true {
				c.succeed++
			} else {
				c.failed++
			}
			c.total++
			//report status every 3 min.
		case <-statTimer.C:
			c.CounterInfo()

		case <-c.quit:
			return
		}
	}
}

func (c *Counter) CounterInfo() {
	log.Printf("Callback information! Total committed: %v,succeed: %v,failed: %v\n", c.total, c.succeed, c.failed)
}
